/**
 * Copyright (c) 2016 Baozun All Rights Reserved.
 *
 * This software is the confidential and proprietary information of Baozun.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Baozun.
 *
 * BAOZUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, OR NON-INFRINGEMENT. BAOZUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 *
 */
package com.discovery.darchrow.web.controller.wechat.oauth;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.discovery.darchrow.net.HttpMethodType;
import com.discovery.darchrow.util.HttpClientUtil;
import com.discovery.darchrow.util.Md5Encrypt;


/**
 * 测试调用由<span style="color:red">app.ufs.xbug.in</span>提供的第三方接口登录授权
 * 
 * @author dongliang.ma
 * @date 2016年11月24日上午9:43:15
 */
@Controller
public class WechatOauthController {
	private static final Logger log = LoggerFactory.getLogger(WechatOauthController.class);
	
	/** 显性*/
//	private static final String SHOW_URL ="http://app.ufs.xbug.in/app-unileverexpiry/unileverapi/oauth";
	//线上
	private static final String SHOW_URL ="http://c2.topchef.net.cn/app-unileverexpiry/unileverapi/oauth";
	
	
	/** 隐性*/
	private static final String HIDE_URL ="http://app.ufs.xbug.in/app-unileverexpiry/unileverapi/oauth2";
	
//	private static final String APP_SECRET="f9381a2f7eabb2b7d017ef6981d90fb2";
	
	//线上
	private static final String APP_SECRET="3f20c67b966b139700f291abb06e43d2";
	
	
	private static final String SECRET_TOKEN="1513dc21f20bc5ac28b62915367fe106";
	
	private static final String SOURCE="44";
	
	private static final String BACK_URL ="http://10.88.33.32:8093/wechat/call-back.htm";

	
	@RequestMapping(value = "/wechat/testOauth.htm", method = RequestMethod.GET)
	public String test(HttpServletRequest request, Model model) {
		
		return "wechat/test-oauth";
	}
	
	@RequestMapping(value = "/wechat/testShowOauth.json", method = RequestMethod.POST)
	@ResponseBody
	public void testShowOauth(Model model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//http://app.ufs.xbug.in/app-unileverexpiry/unileverapi/oauth?
//		secret=f9381a2f7eabb2b7d017ef6981d90fb2&source=12&backurl=http://flab.imcdt.com/haha2.php
		
		NameValuePair[] nameValuePairs =new NameValuePair[4];
		nameValuePairs[0]=new NameValuePair("secret", APP_SECRET);
		nameValuePairs[1]=new NameValuePair("source", SOURCE);
		nameValuePairs[2]=new NameValuePair("backurl", BACK_URL);
		
		Map<String, String> paraMap =new HashMap<String, String>();
		paraMap.put("secret", APP_SECRET);
		paraMap.put("source", SOURCE);
		paraMap.put("backurl", BACK_URL);
		String queryStr =createLinkString(paraMap);
		String sign1 =Md5Encrypt.md5(queryStr);
		String sign =Md5Encrypt.md5(sign1+SECRET_TOKEN);
		nameValuePairs[3]=new NameValuePair("sign", sign);
		
		String res =HttpClientUtil.getPostMethodResponseBodyAsString(SHOW_URL, nameValuePairs);
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter(); 
		out.print(res);
		out.flush();  
        out.close();
	}
	
	public String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }
	
	@RequestMapping(value = "/wechat/testHideOauth.json", method = RequestMethod.POST)
	@ResponseBody
	public void testHideOauth(Model model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String uri =HIDE_URL;
		uri +="?";
		uri +="secret=" + APP_SECRET;
		uri +="&";
		uri +="source=" + SOURCE;
		uri +="&";
		uri +="backurl=" + BACK_URL;
		String res =HttpClientUtil.getHttpMethodResponseBodyAsString(uri, HttpMethodType.GET);
		log.debug("sss:{}", res);
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter(); 
		out.print(res);
		out.flush();  
        out.close();
	}
	
	
	@RequestMapping(value = "/wechat/call-back.htm", method = RequestMethod.GET)
	public String callBack(HttpServletRequest request, Model model,
			@RequestParam("openid")String openid) {
		model.addAttribute("openid", openid);
		Map<String, String> pMap=new HashMap<String, String>();
		for (Map.Entry<String, String[]> entry :request.getParameterMap().entrySet()) {
			pMap.put(entry.getKey(), request.getParameter(entry.getKey()));
		}
		
		model.addAttribute("pMap", pMap);
		return "wechat/call-back";
	}
	
}
